#!/bin/bash
# SonarQube 扫描脚本 - Linux/macOS 版本
# 学生请假管理系统

set -e

echo "========================================"
echo "  SonarQube 代码质量扫描"
echo "  学生请假管理系统"
echo "========================================"
echo ""

# 检查 SONAR_TOKEN 环境变量
if [ -z "$SONAR_TOKEN" ]; then
    echo "[错误] 未设置 SONAR_TOKEN 环境变量"
    echo ""
    echo "请先设置 Token:"
    echo "  export SONAR_TOKEN=your-token-here"
    echo ""
    echo "如何获取 Token:"
    echo "  1. 访问 http://localhost:9000"
    echo "  2. 登录后点击右上角头像"
    echo "  3. My Account > Security > Generate Tokens"
    echo ""
    exit 1
fi

echo "[1/5] 检查 SonarQube 服务..."
if ! curl -s http://localhost:9000/api/system/status > /dev/null 2>&1; then
    echo "[错误] 无法连接到 SonarQube 服务"
    echo "请确保 SonarQube 已启动: docker start sonarqube"
    exit 1
fi
echo "[✓] SonarQube 服务运行正常"

echo ""
echo "[2/5] 检查 SonarScanner..."
if ! command -v sonar-scanner &> /dev/null; then
    echo "[警告] 未找到 sonar-scanner"
    echo "正在尝试使用 npx 运行..."
    USE_NPX=1
else
    echo "[✓] SonarScanner 已安装"
    USE_NPX=0
fi

echo ""
echo "[3/5] 清理旧的扫描缓存..."
rm -rf .scannerwork
echo "[✓] 清理完成"

echo ""
echo "[4/5] 生成测试覆盖率报告..."
cd server
npm run test:coverage || echo "[警告] 测试覆盖率生成失败，继续扫描..."
cd ..
echo "[✓] 测试完成"

echo ""
echo "[5/5] 开始 SonarQube 扫描..."
if [ $USE_NPX -eq 1 ]; then
    npx sonarqube-scanner \
      -Dsonar.host.url=http://localhost:9000 \
      -Dsonar.token=$SONAR_TOKEN
else
    sonar-scanner \
      -Dsonar.host.url=http://localhost:9000 \
      -Dsonar.token=$SONAR_TOKEN
fi

echo ""
echo "========================================"
echo "  扫描完成！✓"
echo "========================================"
echo ""
echo "查看报告: http://localhost:9000/dashboard?id=student-leave-management-system"
echo ""

